<?php


namespace map;


use custom\Curl;
use custom\Err;
use custom\Log;
use think\Exception;

class BaiDu {
    protected static $configs = [
        'ak'   => 'CAG9eY150GAfXkGCLPL69N5CvCpGYjm5',
        'url'  => 'http://api.map.baidu.com/',
        'type' => 'gcj02ll',
    ];

    /**
     * 逆地理编码-通过经纬度获取地址信息
     * @param $lat 纬度
     * @param $lon 经度
     * @param $lang 语言
     * @return bool
     * @throws Exception
     */
    public static function getByLocation($lat, $lon, $lang = '') {
        $url = 'reverse_geocoding/v3';
        $urlData = [
            'location' => "{$lat},{$lon}",
            //            'language' => $lang,
        ];
        $url .= "?" . http_build_query($urlData);
        if (!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'baiduMap.log');
        return $res;
    }

    /**
     * 地理编码-通过地址获取信息
     * @param $address
     * @param string $city
     * @return bool
     * @throws Exception
     */
    public static function getByAddress($address, $city = '') {
        $url = 'geocoding/v3';
        $urlData['address'] = $address;
        $city == '' && $urlData['city'] = $city;
        $url .= "?" . http_build_query($urlData);
        if (!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'baiduMap.log');
        return $res;
    }

    /**
     * 地点检索
     * @param $query
     * @param $city
     * @param string $tag
     * @return bool
     * @throws Exception
     */
    public static function placeSearch($query, $city, $tag = "地铁站") {
        $url = 'place/v2/search';
        $urlData['query'] = $query;
        $urlData['region'] = $city;
        $urlData['tag'] = $tag;
        $urlData['extensions_adcode'] = "true";
        $urlData['coord_type'] = self::$configs['type'];
        $url .= "?" . http_build_query($urlData);
        if (!$res = static::request($url)) {
            return false;
        }
        Log::write($res, 'baiduMap.log');
        return $res;
    }

    /**
     * 百度地图调用
     * @param $url
     * @param array $data
     * @param string $mth
     * @return bool
     * @throws Exception
     */
    public static function request($url, $data = [], $mth = 'GET') {
        $conf = self::$configs;
        $url = $conf['url'] . $url . (strpos($url, '?') ? '&' : '?') . "ret_coordtype={$conf['type']}&ak={$conf['ak']}&output=json";
        $res = Curl::getInstance()->xhr($mth, $url, $data);
        Log::write("map|$url|" . json_encode($data) . '|res:' . json_encode($res), 'baidu_map.log');
        if (empty($res)) {
            Err::add('地图获取失败');
            return false;
        }
        $res = json_decode($res, true);
        if (!isset($res['status'])) {
            Err::add('地图获取失败');
            return false;
        }
        if ($res['status'] != 0) {
            Err::add('地图获取失败');
            return false;
        }

        return $res;
    }
}